package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.client.article.IArticleClient;
import com.heima.client.user.IApUserClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.CommentDto;
import com.heima.model.common.dtos.CommentPageDto;
import com.heima.model.common.dtos.CommentPageDto2;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.wemedia.WmNews;
import com.heima.model.common.pojos.wemedia.WmNewsComment;
import com.heima.model.common.pojos.wemedia.WmUser;
import com.heima.model.common.vo.WmNewsCommentVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmCommentMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojos.ApComment;
import com.heima.wemedia.pojos.ApCommentLike;
import com.heima.wemedia.pojos.ApCommentRepay;
import com.heima.wemedia.pojos.CommentListVo;
import com.heima.wemedia.service.BaiduScanService;
import com.heima.wemedia.service.WmCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service
public class WmCommentServiceImpl extends ServiceImpl<WmCommentMapper, WmNews> implements WmCommentService {

    @Autowired
    private WmCommentMapper wmCommentMapper;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    IApUserClient apUserClient;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private BaiduScanService baiduScanService;

    /**
     * 查看评论接口
     *
     * @param dto
     * @return
     */
    @Override
    public Page<WmNewsCommentVo> findNewsComments(CommentPageDto dto) {
        if (dto == null && dto.getBeginDate() == null && dto.getEndDate() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        Page<WmNewsCommentVo> page = new Page<>(dto.getPage(), dto.getSize());

        //将string类型转为LocalDate类型
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // 创建日期格式器
        // 使用parse方法将字符串按照指定的格式转换为LocalDate
        LocalDate begin = LocalDate.parse(dto.getBeginDate(), formatter);
        LocalDate end = LocalDate.parse(dto.getEndDate(), formatter);
        //转换为LocalDateTime类型
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //远程调用查询文章信息
        Map<String, String> params = new HashMap<>();
        params.put("beginTime",JSON.toJSONString(beginTime));
        params.put("endTime",JSON.toJSONString(endTime));

        String result = iArticleClient.selectNews(params);
        if (StringUtils.isBlank(result)) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<WmNewsComment> wmNewsComments = JSONArray.parseArray(result, WmNewsComment.class);

        List<WmNewsCommentVo> list = new ArrayList<>();
        if (wmNewsComments != null && !wmNewsComments.isEmpty()) {
            for (WmNewsComment wmNewsComment : wmNewsComments) {
                WmNewsCommentVo commentVo = new WmNewsCommentVo();
                //遍历回填数据
                String articleId = wmNewsComment.getId();
                commentVo.setId(articleId);
                commentVo.setTitle(wmNewsComment.getTitle());
                Integer comments = wmNewsComment.getComment();
                if (comments == null) {
                    commentVo.setComments(0);
                } else {
                    commentVo.setComments(comments);
                }
                commentVo.setIsComment(wmNewsComment.getIsComment());
                commentVo.setCreatedTime(wmNewsComment.getCreatedTime());
                //添加集合
                list.add(commentVo);
            }
        }
        page.setRecords(list);
        // 返回分页VO列表
        return page;
    }

    /**
     * 删除评论
     *
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult deleteNewsComments(Integer commentId) {
        mongoTemplate.remove(new Query(Criteria.where("_id").is(commentId)), "ap_comment");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除评论回复
     *
     * @param commentRepayId
     */
    @Override
    public void delCommentRepay(String commentRepayId) {
        if (commentRepayId == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查到当前id的评论回复
        List<ApCommentRepay> commentRepays = mongoTemplate.find(Query.query(Criteria.where("_id").is(commentRepayId)), ApCommentRepay.class);
        mongoTemplate.remove(commentRepays);
    }

    /**
     * 查看评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<CommentListVo> listComment(CommentPageDto2 dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //创建数据类型
        List<CommentListVo> commentRepayListVoList = new ArrayList<>();
        //生成分页
        Page<CommentListVo> page = new Page(dto.getPage(), dto.getSize());
        //查询数据
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        for (ApComment apComment : list) {
            CommentListVo vo = new CommentListVo();
            vo.setApComments(apComment);
            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()));
            query2.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);
            vo.setApCommentRepays(apCommentRepays);
            commentRepayListVoList.add(vo);
        }
        page.setRecords(commentRepayListVoList);
        return page;
    }

    /**
     * 评论点赞
     *
     * @param commentId
     * @param operation
     * @return
     */
    @Override
    public ResponseResult commentlike(String commentId, Integer operation) {
        //查询这条评论数据
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(commentId)),
                ApComment.class);
        if (apComment == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是点赞还是取消点赞
        if (operation == 0) { //0表示点赞
            Integer likes = apComment.getLikes();
            apComment.setLikes(likes+1);
            //重新更新保存评论信息
            mongoTemplate.save(apComment);
            //记录当前用户对于当前评论的数据
            ApCommentLike commentLike = new ApCommentLike();
            commentLike.setCommentId(commentId);
            mongoTemplate.save(commentLike);
        }else { //取消点赞
            Integer likes = apComment.getLikes();
            apComment.setLikes(likes-1);
            //重新更新保存评论信息
            mongoTemplate.save(apComment);
            //删除当前用户对于当前评论的数据
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)),
                    ApCommentLike.class);
        }
        return ResponseResult.okResult(apComment.getLikes());
    }

    /**
     * 回复评论
     *
     * @param commentDto
     * @return
     */
    @Override
    public ResponseResult repayComment(CommentDto commentDto) {
        //参数校验
        if (commentDto == null
                && commentDto.getCommentId() == null
                && commentDto.getContent() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前用户
        Integer useId = WmThreadLocalUtil.get();
        if (useId == null && useId == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //验证发布的评论是否合规
        Integer res = baiduScanService.scanText(commentDto.getContent());
        if (res==0) { //不合格
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取作者用户信息
        WmUser wmUser = wmUserMapper.selectOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId,useId));
        //将数据添加到MongoDB
        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setCommentId(commentDto.getCommentId());
        commentRepay.setContent(commentDto.getContent());
        commentRepay.setAuthorId(useId);
        commentRepay.setLikes(0);
        commentRepay.setAuthorName(wmUser.getName());
        commentRepay.setCreatedTime(new Date());
        commentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(commentRepay);
        //远程调用添加评论数量
        Query query = new Query(Criteria.where("_id").is(commentDto.getCommentId()));
        // 执行查询，获取整行数据
        ApComment comment = mongoTemplate.findOne(query, ApComment.class, "ap_comment");
        iArticleClient.saveComment(comment.getEntryId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 打开或关闭评论
     *
     * @param commentDto
     * @return
     */
    @Override
    public ResponseResult updateCommentStatus(CommentDto commentDto) {
        //参数校验
        if (commentDto == null
                && commentDto.getArticleId() == null
                && commentDto.getOperation() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据articleId修改文章评论状态
        //远程调用修改文章评论状态
        iArticleClient.updateComment(commentDto.getArticleId(), commentDto.getOperation());
        if (commentDto.getOperation() == 0) {
            //关闭评论则要清空评论
           // mongoTemplate.remove(new Query(Criteria.where("entryId").is(commentDto.getArticleId())), "ap_comment");
            mongoTemplate.remove(Query.query(Criteria.where("entryId").is(commentDto.getArticleId())),ApComment.class);
            //远程调用情况article的评论数量
            iArticleClient.deleteNews(commentDto);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




